<?php
class TestTopics extends CActiveRecord {
	const SESSION_KEY_PREFIX = 'testTopic';
	const STATUS_PUBLISHED = 1;
	const STATUS_UNPUBLISHED = 0;
	const TYPE_MARK_SINGLE_CONLUSION = 1;
	const TYPE_MARK_MULTI_CONLUSIONS = 2;
    const TYPE_JUMPING = 3;
    const IMAGE_SUFFIX_M = 'm';
    const IMAGE_SUFFIX_S = 's';
    const IMAGE_WIDTH_S = 100;
    const IMAGE_HEIGHT_S = 70;
    const IMAGE_WIDTH_M = 200;
    const IMAGE_HEIGHT_M = 140;
    const IMAGE_EXT = '.jpg';

//    public function safeAtrributes() {
//    	return array('metaKey');
//    }

	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	public function tableName() {
		return strtolower('PsyTestTopics');
	}
	
	public function rules() {
		return array(
			array('topicTitle, topicDescr', 'required'),
            array('topicImage', 'required'),
//			array('topicImage', 'file', 'maxSize' => 1024*1024*5, 'types' => 'gif, jpg, png', 'on' => 'new')
		);
	}
    
    public function relations() {
        return array(
            'questions' => array(self::HAS_MANY, 'TestQuestions', 'topicId',
                'joinType'=> 'LEFT JOIN',
                'order' => 'questionOrder'
            ),
            'conclusions' => array(self::HAS_MANY, 'TestConclusions', 'topicId',
                'joinType' => 'LEFT JOIN',
                'order' => 'conclusionOrder',
                'condition' => 'conclusionOrder != 0'
            ),
            'generalConclusion' => array(self::HAS_ONE, 'TestConclusions', 'topicId',
                'joinType' => 'LEFT JOIN',
                'condition' => 'conclusionOrder = 0'
            ),
            'dimens' => array(self::HAS_MANY, 'TestDimens', 'topicId',
                'joinType' => 'LEFT JOIN',
            ),
            'comments' => array(self::HAS_MANY, 'TestComments', 'topicId',
            	'joinType' => 'LEFT JOIN'
            ),
            'category' => array(self::BELONGS_TO, 'TestCategories', 'psyTestCategoryId',
                'joinType' => 'LEFT JOIN'
            ),
            'secDims' => array(self::HAS_MANY, 'TestSecDims', 'topicId',
                'joinType' => 'LEFT JOIN',
            )
        );
    }

    public function scopes() {
        return array(
            'published' => array(
                'condition' => 'topicStatus = '.self::STATUS_PUBLISHED
            )
        );
    }

	public function attributeLabels() {
		return array(
			'topicTitle' => '标题',
			'topicDescr' => '描述',
            'topicImage' => '主题图片'
		);
	}

    public function afterDelete() {
    	foreach($this->questions as $question) {
    		$question->delete();
    	}
    	foreach($this->dimens as $dim) {
    		$dim->delete();
    	}
    	foreach($this->conclusions as $conclusion) {
    		$conclusion->delete();
    	}
    	foreach($this->comments as $comment) {
    		$comment->delete();
    	}
        if($this->category !== null) {
            $this->category->updatePsytestCount();
        }
    }

    public function afterSave() {
        if($this->isNewRecord && $this->category !== null) {
            $this->category->updatePsytestCount();
        }
    }

    public function getImageFilename($suffix) {
    	return $this->topicImage.'_'.$suffix.self::IMAGE_EXT;
    }

    static public function suffix2Size() {
    	return array(
    		self::IMAGE_SUFFIX_M => array(self::IMAGE_WIDTH_M, self::IMAGE_HEIGHT_M),
    		self::IMAGE_SUFFIX_S => array(self::IMAGE_WIDTH_S, self::IMAGE_HEIGHT_S)
    	);
    }
    
    static public function getSize($suffix) {
    	$suffix2Size = self::suffix2Size();
    	return isset($suffix2Size[$suffix]) ? $suffix2Size[$suffix2Size] : null;
    }
    
    public function generateImageFilename() {
    	$this->topicImage = $this->topicId.'_'.time();
    }

    public function getImagePath($suffix) {
    	return UPLOADS_PSYTOPIC_IMAGE.DIRECTORY_SEPARATOR.$this->getImageFilename($suffix);
    }
    
    public function getImageUrl($suffix) {
    	return Yii::app()->getBaseUrl(true).'/'.UPLOADS_PSYTOPIC_IMAGE.'/'.$this->getImageFilename($suffix);
    }
    
    static public function status2Text() {
    	return array(
    		self::STATUS_UNPUBLISHED => '未发布',
    		self::STATUS_PUBLISHED => '已发布'
    	);
    }
    
    static public function topicType2Text() {
    	return array(
    		self::TYPE_MARK_SINGLE_CONLUSION => '记分式单结论',
    		self::TYPE_MARK_MULTI_CONLUSIONS => '记分式多结论组合',
            self::TYPE_JUMPING => '跳转式'
    	);
    }
    
    static public function hasSecDimOptions() {
    	return array(
    		0 => '否',
    		1 => '是'
    	);
    }
    
    public function getHasSecDimText() {
    	$secDimOptions = self::hasSecDimOptions();
    	return isset($secDimOptions[$this->hasSecDim]) ? $secDimOptions[$this->hasSecDim] : '未知 #'.$this->hasSecDim;
    	
    }
    
    public function getStatusText() {
    	$status2Text = self::status2Text();
    	return isset($status2Text[$this->topicStatus]) ? $status2Text[$this->topicStatus] : '未知状态 #'.$this->topicStatus;
    }
    
    public function getTopicTypeText() {
    	$topicTypeText = self::topicType2Text();
    	return isset($topicTypeText[$this->topicType]) ? $topicTypeText[$this->topicType] : '未知 #'.$this->topicType;
    }

    static public function getMarkTypes() {
        return array(self::TYPE_MARK_SINGLE_CONLUSION, self::TYPE_MARK_MULTI_CONLUSIONS);
    }

    static public function typeCatalogs() {
    	return array(
    		self::TYPE_MARK_SINGLE_CONLUSION => 'mark',
    		self::TYPE_MARK_MULTI_CONLUSIONS => 'mark',
            self::TYPE_JUMPING => 'jumping'
        );
    }

    public function getTypeCatalog() {
        $markTypes = self::typeCatalogs();
        return isset($markTypes[$this->topicType]) ? $markTypes[$this->topicType] : '未知 #'.$this->topicType;
    }

    public function getSessionKey() {
        return self::SESSION_KEY_PREFIX.'_'.$this->topicId;
    }

    public function getState() {
        return Yii::app()->user->hasState($this->getSessionKey()) ? Yii::app()->user->getState($this->getSessionKey()) : array();
    }
    
    public function getStateCount() {
    	return count($this->getState());
    }

    public function setState($state) {
        return Yii::app()->user->setState($this->getSessionKey(), $state);
    }

    public function hasState() {
        return Yii::app()->user->hasState($this->getSessionKey());
    }

    public function resetState() {
        return $this->setState(array());
    }

    public function hasTested() {
        if($userId = Yii::app()->user->id) {
            $userPsytest = UserPsytest::model()->findByAttributes(array('topicId' => $this->topicId, 'userId' => $userId));
            return $userPsytest !== null ? $userPsytest : false;
        }
        return false;
    }
}
